import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, customResponse } from '~/utils/response';
import { type instType, INSTRUMENTS_DATA, queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    let queryString;
    const args = [];
    // 读取POST请求的参数
    const { sampleNo, sampleName, data: reportTable } = await readBody(event);
    if (!sampleNo || !sampleName || !reportTable) throw new Error('请求参数不完整！');
    // 解析data参数为数组
    const cloneData = JSON.parse(reportTable);

    // 处理检测依据
    let maxCount = 0; // 初始化最大次数为0
    const conclusionMap: Record<string, number> = {}; // 创建一个Map来存储检测结论及其出现次数
    const methodMap: Record<string, number> = {}; // 创建一个Map来存储检测方法及其出现次数
    const uniqueMethods = new Set<string>(); // 创建一个Set来存储唯一的检测方法

    queryString = `SELECT sampleName, testItems, DATE_FORMAT(analysisDate, '%Y-%m-%d') AS analysisDate FROM samplelists WHERE sampleNo = ? `;
    const res = <any[]>await queryDatabase(queryString, sampleNo);
    if (res.length <= 0) throw new Error('样品编号不存在！');

    const reportDate = res[0].analysisDate;
    const sampleNameArr = JSON.parse(res[0].sampleName); // 将sampleName转换为数组
    const testItems = res[0].testItems; // 将testItems转换为数组

    cloneData.forEach((item) => {
      const { testMethod, tConc: testConclusion } = item;
      conclusionMap[testConclusion] = (conclusionMap[testConclusion] || 0) + 1;

      uniqueMethods.add(testMethod);
      methodMap[testMethod] = (methodMap[testMethod] || 0) + 1;
      if (methodMap[testMethod] > maxCount) {
        maxCount = methodMap[testMethod];
      }
    });

    // 主方法和< 检测依据 >
    const mainMethod = Object.keys(methodMap).filter((key) => methodMap[key] === maxCount)[0];
    const refDocs = Array.from(uniqueMethods).join('\n');
    // console.log('检测依据：', refDocs);
    // console.log('主方法：' + mainMethod, `\n`);

    // 检测结论
    let resultsWords: string;
    const wordA = `经检测，受检样品所检测项目均符合${mainMethod.split('《')[0]}中${sampleName}(${
      sampleNameArr.slice(-1)[0]
    })的技术指标要求。`;
    const wordB = Object.entries(conclusionMap)
      .map(([key, value]) => `${key}${value}项`)
      .join(`，`);
    const wordZ = `经检测，根据${mainMethod.split('《')[0]}中${sampleName}(${
      sampleNameArr.slice(-1)[0]
    })的技术指标要求，受检样品所检测项目${wordB}，详见下页。`;
    if (['天然气', '液化石油气', '丙烯', '乙烯', '空气'].includes(sampleName)) {
      resultsWords = '仅提供测试数据，不进行符合性判定。';
    } else {
      resultsWords = conclusionMap['合格'] === Object.keys(conclusionMap).length ? wordA : wordZ;
    }
    // console.log('检测结论：' + resultsWords, `\n`);

    // 检测仪器
    let instTable: instType[] = [];
    const pureGas = ['Helium', 'Nitrogen', 'Argon', 'Oxygen', 'CarbonDioxide', 'Hydrogen', 'Methane', 'CarbonMonoxide'];
    if (pureGas.includes(sampleNameArr.slice(0)[0])) {
      // 纯气
      switch (testItems) {
        case '成分分析':
          instTable.push(INSTRUMENTS_DATA['RTYF-002-7']);
          cloneData.forEach((item) => {
            if (item.tItem.startsWith('水分(H<sub>2</sub>O)含量')) {
              instTable.push(INSTRUMENTS_DATA['RTYF-008-2']);
            } else if (item.tItem.startsWith('氧(O<sub>2</sub>)含量')) {
              instTable.push(INSTRUMENTS_DATA['RTYF-009-1']);
            }
          });
          break;
        case '氧含量':
          instTable.push(INSTRUMENTS_DATA['RTYF-009-1']);
          break;
        case '水含量':
          const isOld = parseInt(reportDate.replace('-', '')) <= 20241129;
          instTable.push(INSTRUMENTS_DATA[isOld ? 'RTYF-008-2-old' : 'RTYF-008-2']);
          break;
        default:
          throw new Error('未知测试项目，无法列举仪器！');
      }
    } else {
      // 其他气
      switch (sampleNameArr.slice(0)[0]) {
        case '天然气':
          instTable.push(INSTRUMENTS_DATA['RTYF-002-10']);
          break;
        case '液化石油气':
          instTable.push(INSTRUMENTS_DATA['RTYF-002-11']);
          break;
        case '乙烯':
          instTable.push(testItems === '烃类杂质' ? INSTRUMENTS_DATA['RTYF-002-10'] : INSTRUMENTS_DATA['RTYF-002-6']);
          break;
        case '丙烯':
          instTable.push(testItems === '烃类杂质' ? INSTRUMENTS_DATA['RTYF-002-10'] : INSTRUMENTS_DATA['RTYF-002-6']);
          break;
        case '空气':
          instTable.push(testItems === '甲烷含量' ? INSTRUMENTS_DATA['RTYF-002-4'] : INSTRUMENTS_DATA['RTYF-003-1']);
          break;
        case '标准物质':
          // 标准物质不列举仪器
          break;
        default:
          throw new Error('未知样品，无法列举仪器！');
      }
    }
    // console.log('检测仪器：', instTable, `\n`);

    // 写入数据库
    queryString = `UPDATE samplelists SET reportTable = ? , instTable = ? , refDocs = ? , resultsWords = ? , currentProgress = ?  WHERE sampleNo = ?`;
    args.push(reportTable, JSON.stringify(instTable), refDocs, resultsWords, '报告审核', sampleNo);

    await queryDatabase(queryString, args);
    return useResponseSuccess('提交成功！');
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
